import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { RoleItem } from '@/types/role'
import RoleService from '@/api/role'

export const useRoleStore = defineStore('role', () => {
    const roles = ref<RoleItem[]>([])
    const currentRole = ref<RoleItem>()

    // 获取角色列表
    const fetchRoles = async () => {
        const data = await RoleService.list()
        roles.value = data
        return roles.value
    }

    // 设置当前角色
    const setCurrentRole = (roleId: number | null) => {
        currentRole.value = roles.value.find(role => role.id === roleId)
    }

    // 是否是管理员
    const isSuperAdmin = computed(() => currentRole.value?.type == 3)

    // 是否是老师
    const isTeacher = computed(() => currentRole.value?.type == 2)

    // 是否是学生
    const isStudent = computed(() => currentRole.value?.type == 1)

    // 获取当前角色信息
    const getCurrentRoleInfo = (roleId: number) => {
        if (!currentRole.value) setCurrentRole(roleId)
        return roles.value.find(role => role.id === roleId)
    }

    return { roles, currentRole, isSuperAdmin, isTeacher, isStudent, fetchRoles, setCurrentRole, getCurrentRoleInfo }
})
